package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"product_zc/models/cache"
	"product_zc/models/mysql"
	"time"

	"product_zc/productRpc/internal/svc"
	"product_zc/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProductLogic {
	return &ListProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProductLogic) ListProduct(in *productRpc.ListProductRequest) (*productRpc.ListProductResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	var products []mysql.Product
	key := fmt.Sprintf("productsList%d%d", in.Page, in.Size)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()

	if cacheData == "" {

		query := mysql.DB.Debug()

		if in.Title != "" {
			query = query.Where("title=?", in.Title)
		}

		query = query.Offset(int(offset)).Limit(int(pageSize)).
			Order("price desc").Find(&products)

		marshal, _ := json.Marshal(products)
		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(cacheData), &products)
	}

	var productsList []*productRpc.ListProduct
	for _, product := range products {
		list := productRpc.ListProduct{
			Id:     int64(product.ID),
			Title:  product.Title,
			Price:  float32(product.Price),
			UserId: product.UserId,
		}

		productsList = append(productsList, &list)
	}

	return &productRpc.ListProductResponse{
		List: productsList,
	}, nil
}
